import 'dart:async';

class DataBloc {
  // 定义Controller
  StreamController<List<String>> _dataController = StreamController();

  late Function(List<String> s) callback;

  // 获取StreamSink做add入口
  StreamSink<List<String>> get _dataSink => _dataController.sink;

  // 获取Stream用于监听
  Stream<List<String>> get dataStream => _dataController.stream;

  late StreamSubscription _dataSubscription;

  init(Function(List<String> s) callback) {
    this.callback = callback;
    _dataSubscription = dataStream.listen(_onDataChange, onDone: () {
      print("DataBloc onDone");
    }, onError: (e) {
      print("DataBloc onError:$e");
    }, cancelOnError: true);
  }

  add(String s) {
    _dataSink.add([s]);
  }

  close() {
    _dataSubscription.cancel();
    _dataController.close();
  }

  void _onDataChange(List<String> data) {
    print("DataBloc _onDataChange: $data");
    if (callback != null) callback.call(data);
  }
}
